import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';

declare module 'express' {
  interface Request {
    user?: any;
  }
}

@Injectable()
export class LoginGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();

    if (request.headers.authorization) {
      const token = request.headers.authorization.split(' ')[1];
      try {
        const decoded = this.jwtService.verify(token, { secret: '123123' });
        request.user = decoded;
        return true;
      } catch (err) {
        return false;
      }
    }
    return true;
  }
}
